/*
 *	CHANGE LOG
 * 
 * 01.02.08
 *
 *				   - DW - Changed the name of GetModuleInfo to GetModulesForUser to be more consistent with
 *							what it does.  This particular overload was only called from the Help, FAQ and 
 *							Announcements providers.  Also changed the implementation to remove a break 
 *							which was causing the procedure to only return the top most module.
 * 
 *		12/08/2008 - DW - Changed SaveItemImages to set the folder permissions after an item is saved.
 * 
 *  01.02.02
 * 
 *		01/20/2009 - DW - Changed the implementation of the GetString methods to allow the calling procedure
 *							to specify language.
 *  01.02.03
 *  
 *      11/30/2009 - DW - Closed the data readers when connections are made to the db. 
 */


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Web;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework.Providers;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;

namespace ITCrossing
{

	public class MetaPostServices
	{

		# region Private Static Fields
		private static ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
		private static string				_connectionString;
		private static string				_providerPath;
		private static string				_objectQualifier;
		private static string				_databaseOwner;
		# endregion

		# region Public Static Properties
		public static string DatabaseOwner
		{
			get
			{
				if (string.IsNullOrEmpty(_databaseOwner))
				{
					// Read the configuration specific information for this provider
					Provider objProvider = (Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider];

					_databaseOwner = objProvider.Attributes["databaseOwner"];
					if ((_databaseOwner != "") && !_databaseOwner.EndsWith("."))
						_databaseOwner += ".";

				}
				return _databaseOwner;
			}
		}
		public static string ObjectQualifier
		{
			get
			{
				if (string.IsNullOrEmpty(_objectQualifier))
				{
					// Read the configuration specific information for this provider
					Provider objProvider = (Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider];

					_objectQualifier = objProvider.Attributes["objectQualifier"];
					if ((_objectQualifier != "") && !_objectQualifier.EndsWith("_"))
						_objectQualifier += "_";

				}
				return _objectQualifier;
			}
		}		
		# endregion

		# region Public Static Procedures

		/// <summary>
		/// AuthorizeUser checks to make sure this user still has edit rights to this module.  If not, then 
		/// we return false.
		/// </summary>
		/// <param name="moduleId"></param>
		/// <returns>True if the user has edit access and false if not</returns>
		/// <param name="modulesAuthorizedForUser"></param>
		public static void						AuthorizeUser(AuthorizationType authType, string moduleId, ModuleInfoStruct[] modulesAuthorizedForUser)
		{
			bool isAuthorized = false;

			foreach(ModuleInfoStruct mis in modulesAuthorizedForUser)
			{
				if (authType == AuthorizationType.ModuleLevelId && mis.ModuleLevelId == moduleId)
				{
					isAuthorized = true;
					break;
				}
				else if (authType == AuthorizationType.DnnModuleId && mis.DnnModuleId.ToString() == moduleId)
				{
					isAuthorized = true;
					break;
				}
			}

			if (!isAuthorized) throw new MetaPostException("ActionNotAuthorized", "The action requested is not authorized for the current user account.", true);

		}
		
		public static bool						ContainsHtml(string content)
		{
			bool retValue = false;
			string regex = @"<(?:div|table|span|tr|p|a|h\d|td|ul|li|blockquote|font)+[^>]*>";
			RegexOptions options = RegexOptions.Singleline | RegexOptions.IgnoreCase;

			MatchCollection matches = Regex.Matches(content, regex, options);

			if (matches.Count > 0)
			{
				retValue = true;
			}
			return retValue;
		}

		public static string					GetAppPath()
		{
			string appPath = HttpContext.Current.Request.ApplicationPath;
			if (appPath == "/") appPath = string.Empty;
			return appPath;
		}

        public static decimal                   GetDnnVersion()
        {
            decimal dnnVersion = 0;

            string SQL = "SELECT  TOP 1 Major, Minor, Build FROM {databaseOwner}[{objectQualifier}Version](nolock) ORDER BY VersionId DESC";

            using (IDataReader dr = DataProvider.Instance().ExecuteSQL(SQL))
            {
                while (dr.Read())
                {
                    int major = dr.GetInt32(dr.GetOrdinal("Major"));
                    int minor = dr.GetInt32(dr.GetOrdinal("Minor"));
                    int build = dr.GetInt32(dr.GetOrdinal("build"));
                    dnnVersion = major + minor / 100m + build / 10000m;
                }
            }

            return dnnVersion;
        }
        
        public static List<DnnModuleInfoStruct> GetEditableModules(string providerKey, int userId, int portalId)
		{
			List<DnnModuleInfoStruct> moduleInfos = new List<DnnModuleInfoStruct>();

			// Return the Module Information For the current providerKey
			string sSQL = "itcMetaPost_Get_Modules_With_Edit_Permission";

			object[] methodParams = { providerKey, userId, portalId };
            using (IDataReader dr = DotNetNuke.Data.DataProvider.Instance().ExecuteReader(sSQL, methodParams))
            {

                while (dr.Read())
                {
                    DnnModuleInfoStruct moduleInfo = new DnnModuleInfoStruct();
                    moduleInfo.ModuleId = dr.GetInt32(dr.GetOrdinal("ModuleId"));
                    moduleInfo.TabId = dr.GetInt32(dr.GetOrdinal("TabId"));
                    moduleInfo.TabModuleId = dr.GetInt32(dr.GetOrdinal("TabModuleId"));
                    moduleInfo.TabPath = dr.GetString(dr.GetOrdinal("TabPath"));
                    moduleInfo.ModuleTitle = dr.GetString(dr.GetOrdinal("ModuleTitle"));
                    if (!dr.IsDBNull(dr.GetOrdinal("CreatedDate")))
                        moduleInfo.CreatedDate = dr.GetDateTime(dr.GetOrdinal("CreatedDate"));
                    moduleInfos.Add(moduleInfo);
                }
            }

			return moduleInfos;
		}

		public static string					GetFooterContent(string providerKey)
		{
			string footerContent = string.Empty;

			string SQL =
				"itcMetaPost_Get_FooterTemplate_By_ProviderKey";
			object[] methodParams = { providerKey.Replace("'", "''") };
			footerContent = DataProvider.Instance().ExecuteScalar(SQL, methodParams) as string;

			if (footerContent != null)
			{
				footerContent = HttpUtility.HtmlDecode(footerContent);
			}
			else
			{
				footerContent = string.Empty;
			}

			return footerContent;
		}
		
		public static string					GetFriendlyNameFromModuleDefinition(string moduleDefinition)
		{
			string friendlyName;

			string SQL = "itcMetaPost_Get_DesktopModule_FriendlyName";
			object[] methodParams = { moduleDefinition };
			friendlyName = (string)DataProvider.Instance().ExecuteScalar(SQL, methodParams);

			return friendlyName;
		}

		public static List<string>				GetImageListFromItem(ref Item item)
		{
			List<string> imageUrls = new List<string>();

			try
			{
				string regexSrc = "<img[^>]+?_itc_new_image_/.*?>";
				string regexHref = "<a[^>]+?(?:png|jpg|jpeg|gif)[^>]+?>[^<]*?<img[^>]+?src=\"[^\"]+?\"[^>]+>[^<]*?</a>";
				// Note that the inner Regex patterns required a group named 'src'
				string regexInnerSrc = "src=\"(?<src>[^\"]+?)\"";
				string regexInnerHref = "href=\"(?<src>[^\"]+?)\"";

				RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;
				string input = item.Summary + item.Content + item.ExtendedContent;

				if (!string.IsNullOrEmpty(input))
				{
					FindImageMatch(input, regexSrc, regexInnerSrc, options, imageUrls);
					FindImageMatch(input, regexHref, regexInnerHref, options, imageUrls);
				}

				// Remove the unique string from the content.
				if (!string.IsNullOrEmpty(item.Content))
					item.Content = item.Content.Replace("_itc_new_image_/", string.Empty);
				if (!string.IsNullOrEmpty(item.Summary))
					item.Summary = item.Summary.Replace("_itc_new_image_/", string.Empty);
				if (!string.IsNullOrEmpty(item.ExtendedContent))
					item.ExtendedContent = item.ExtendedContent.Replace("_itc_new_image_/", string.Empty);
			}
			catch (Exception ex)
			{
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
			return imageUrls;

		}
			/// <summary>
			/// GetModuleInfo(tabModuleId) returns only the ModuleId and TabId
			/// for a TabModuleId.  The rest of the fields in the DnnModuleInfoStruct are
			/// ignored.
			/// </summary>
			/// <param name="tabModuleId"></param>
			/// <returns></returns>
		public static DnnModuleInfoStruct		GetModuleInfo(int tabModuleId)
		{
			DnnModuleInfoStruct moduleInfo = new DnnModuleInfoStruct();

			// Return the Module Information For the current providerKey
			string sSQL = "itcMetaPost_Get_Module_Fields_By_TabModuleId";

			object[] methodParams = { tabModuleId };
            using (IDataReader dr = DotNetNuke.Data.DataProvider.Instance().ExecuteReader(sSQL, methodParams))
            {

                while (dr.Read())
                {
                    moduleInfo.ModuleId = dr.GetInt32(dr.GetOrdinal("ModuleId"));
                    moduleInfo.TabId = dr.GetInt32(dr.GetOrdinal("TabId"));
                }
            }

			return moduleInfo;
		}

		public static ModuleInfoStruct[]		GetModulesForUser(string providerKey, int userId, int portalId)
		{
			List<ModuleInfoStruct> moduleInfoList = new List<ModuleInfoStruct>();

			List<DnnModuleInfoStruct> dnnModuleInfoList =
				GetEditableModules(
					providerKey, userId, portalId);
			foreach (DnnModuleInfoStruct dnnModuleInfoStruct in dnnModuleInfoList)
			{
				ModuleInfoStruct moduleInfo = new ModuleInfoStruct();
				moduleInfo.ModuleLevelId = dnnModuleInfoStruct.TabModuleId.ToString();
				moduleInfo.DnnModuleId = dnnModuleInfoStruct.ModuleId;
				string modulePath = dnnModuleInfoStruct.TabPath.Replace("//", "/");
				// remove the beginning forward slash
				if (modulePath.Length > 1 && modulePath.Substring(0, 1) == "/")
					modulePath = modulePath.Substring(1);
				moduleInfo.ModuleName = dnnModuleInfoStruct.ModuleTitle + " (" + modulePath + ")";

				moduleInfo.Url = MetaPostServices.GetRedirectUrl(providerKey, dnnModuleInfoStruct.TabId);
				moduleInfoList.Add(moduleInfo);
				// DW - 11/26/2008 - ??? How did this break get in here?
				//break;
			}
			return moduleInfoList.ToArray();
		}

		public static List<DnnModuleInfoStruct> GetModuleInfos(string providerKey, int portalID)
		{
			List<DnnModuleInfoStruct> moduleInfos = new List<DnnModuleInfoStruct>();
			
			// Return the Module Information For the current providerKey
			string sSQL = "itcMetaPost_Get_Module_Fields_By_FriendlyName";

			object[] methodParams = { providerKey, portalID };
            using (IDataReader dr = DotNetNuke.Data.DataProvider.Instance().ExecuteReader(sSQL, methodParams))
            {

                while (dr.Read())
                {
                    DnnModuleInfoStruct moduleInfo = new DnnModuleInfoStruct();
                    moduleInfo.ModuleId = dr.GetInt32(dr.GetOrdinal("ModuleId"));
                    moduleInfo.TabId = dr.GetInt32(dr.GetOrdinal("TabId"));
                    moduleInfo.TabModuleId = dr.GetInt32(dr.GetOrdinal("TabModuleId"));
                    moduleInfo.TabPath = dr.GetString(dr.GetOrdinal("TabPath"));
                    moduleInfos.Add(moduleInfo);
                }
            }

			return moduleInfos;
		}

		public static int						GetModuleIdByTabModuleId(int tabModuleId)
		{
			return GetModuleInfo(tabModuleId).ModuleId;
		}

		public static string					GetProviderImageUploadPath(string providerKey)
		{
			string sURL = "";

			try
			{
				// Retrieve the upload URL from the module's settings
				string sSQL =
					"SELECT ImagePath FROM {databaseOwner}{objectQualifier}itcMetaPostProviders (nolock) WHERE ProviderKey = N'"
					+ providerKey.Replace("'", "''") + "'";
                using (IDataReader dr =
                    (IDataReader)DataProvider.Instance().ExecuteSQL(sSQL))
                {
                    while (dr.Read())
                    {
                        sURL = dr["ImagePath"].ToString() + "";
                    }
                }
			}
			catch
			{
			} // If we fail, we just set to a default value.

			// Make sure we don't have a beginning forward slash.
			if (!string.IsNullOrEmpty(sURL) && sURL.Substring(0, 1) == "/") sURL = sURL.Substring(1);

			// Set to default value in case this value can't be retrieved for some reason.
			if (string.IsNullOrEmpty(sURL)) sURL = "";

			return sURL;
		}

		public static string GetProviderAttachmentUploadPath(string providerKey)
		{
			string sURL = "";

			try
			{
				// Eventually, we'll need code similar to this.  for now, we'll hard code this to the 
				// following:

				sURL = "attachments/[Provider]/[FolderFilePath]";
				//// Retrieve the upload URL from the module's settings
				//string sSQL =
				//    "SELECT ImagePath FROM {databaseOwner}{objectQualifier}itcMetaPostProviders WHERE ProviderKey = N'"
				//    + providerKey.Replace("'", "''") + "'";
				//IDataReader dr =
				//    (IDataReader)DataProvider.Instance().ExecuteSQL(sSQL);
				//while (dr.Read())
				//{
				//    sURL = dr["ImagePath"].ToString() + "";
				//}
			}
			catch
			{
			} // If we fail, we just set to a default value.

			// Make sure we don't have a beginning forward slash.
			if (!string.IsNullOrEmpty(sURL) && sURL.Substring(0, 1) == "/") sURL = sURL.Substring(1);

			// Set to default value in case this value can't be retrieved for some reason.
			if (string.IsNullOrEmpty(sURL)) sURL = "";

			return sURL;
		}


		public static string	GetRedirectUrl(string providerKey, int TabId)
		{
			string appPath = GetAppPath();
			string urlGUID;
			string returnUrl = appPath + "/DesktopModules/itcMetaPost/metaPostRedirect.ashx?key=" + providerKey + "&urlkey=";

			string sSQL = "itcMetaPost_Get_Blog_Redirect_URL_Key";

			object[] methodParams = { TabId, providerKey, Globals.NavigateURL(TabId)};

			// Get the URL Key for the Redirect URL.  This sproc will create the URL key if it doesn't exist.
			urlGUID = DataProvider.Instance().ExecuteScalar(sSQL, methodParams).ToString();
			
			return returnUrl + urlGUID;
		}
			/// <summary>
			/// GetDnnModuleInfoStructByTabModuleId return only the ModuleId and TabId
			/// for a TabModuleId.  The rest of the fields in the DnnModuleInfoStruct are
			/// ignored.
			/// </summary>
			/// <param name="tabModuleId"></param>
			/// <returns></returns>
		public static string					GetStringGlobal(string key, string defaultValue, string language)
		{
			return GetString(key, defaultValue, "/DesktopModules/itcMetaPost/App_LocalResources/itcMetaPost", language);
		}

		public static string					GetString(string key, string defaultValue, string localizationFilePath, string language)
		{
			string retValue = Localization.GetString(key, localizationFilePath, language);
			return retValue ?? defaultValue;
		}

		public static string					GetTempStyleValue(int userId, string key)
		{
			string retValue = string.Empty;

			object[] methodParams = {userId,key};
			string SQL = "itcmetapost_retrieve_and_remove_temp_style_text";
			retValue = DotNetNuke.Data.DataProvider.Instance().ExecuteScalar(SQL, methodParams) as string;

			return retValue;
		}

		public static void						RefreshCache(ModuleInfo moduleInfo, ModuleController moduleController)
		{
			// We need to use reflection to call the SynchronizeModule static method of the ModuleController object
			// since it's not supported in older versions of DotNetNuke
			try
			{
				MethodInfo mi = moduleController.GetType().GetMethod("SynchronizeModule");
				mi.Invoke(null, new object[] { moduleInfo.ModuleID });
			}
			catch { }
		}
		public static void						RefreshCache(int moduleId)
		{
			// Clear the cache
			ModuleController moduleController = new ModuleController();
			ModuleInfo moduleInfo = moduleController.GetModule(moduleId, Null.NullInteger, false);

			RefreshCache(moduleInfo, moduleController);
		}

		public static void						SaveItemImages(int itemId, List<string> images, string providerKey, PortalSettings  portalSettings,int UserId)
		{
			string folderPathAndFile = string.Empty;
			string folderPath = string.Empty;
			string fileName = string.Empty;
			string physicalPath = string.Empty;
			int fileId = 0;
			int folderId = 0;

			if (images.Count > 0)
			{
				// Parse the image information to find the folder and file information
				// and then create new entries in the DNN Folders and Files tables if 
				// needed for the new entry.
				FolderController folderController = new FolderController();
				FolderInfo folderInfo = null;

				foreach (string image in images)
				{
					try
					{
						folderPathAndFile =
							image.Substring(image.IndexOf(portalSettings.HomeDirectory) +
							                portalSettings.HomeDirectory.Length);
						physicalPath = portalSettings.HomeDirectoryMapPath
						               + folderPathAndFile.Replace("/", @"\");
						// It turns out that we need to grab this before we save the folder since
						// it appears that DNN doesn't release the handle to the folder when it creates
						// the folder.
						ImageFileInfo imageFileInfo = GetImageFileInformation(physicalPath);
						fileName = image.Substring(image.LastIndexOf("/") + 1);
						folderPath = folderPathAndFile.Substring(0, folderPathAndFile.LastIndexOf("/") + 1);
						folderInfo = folderController.GetFolder(portalSettings.PortalId, folderPath);
						if (folderInfo == null)
						{
							try
							{
								folderId = folderController.AddFolder(portalSettings.PortalId, folderPath);
								// Set the folder permissions
								// Administrators get read and write
								FileSystemUtils.SetFolderPermissions(portalSettings.PortalId, folderId, portalSettings.AdministratorRoleId, folderPath);
								// Logged in user gets read and write
								MethodInfo[] miArray = typeof (FileSystemUtils).GetMethods();
								MethodInfo miNewVersion = null;
								MethodInfo miOldVersion = null;
								foreach (MethodInfo mi in miArray)
								{
									if (mi.Name == "SetFolderPermission")
									{
										if (mi.GetParameters().Length == 5) miOldVersion = mi;
										if (mi.GetParameters().Length == 6) miNewVersion = mi;
									}
									if (miNewVersion != null) break;
								}
								if (miOldVersion != null || miNewVersion != null)
								{
									object[] mParams = null;
									if (miNewVersion != null)
									{
										mParams = new object[6];
										mParams.SetValue(portalSettings.PortalId, 0);
										mParams.SetValue(folderId, 1);
										mParams.SetValue(5, 2);
										mParams.SetValue(null, 3);
										mParams.SetValue(UserId, 4);
										mParams.SetValue(folderPath, 5);
										miNewVersion.Invoke(null, mParams);
										mParams.SetValue(6,2);
										miNewVersion.Invoke(null, mParams);
									}
									else if (miOldVersion != null)
									{
										mParams = new object[5];
										mParams.SetValue(portalSettings.PortalId, 0);
										mParams.SetValue(folderId, 1);
										mParams.SetValue(5, 2);
										mParams.SetValue(-1, 3);
										mParams.SetValue(folderPath, 4);
										miOldVersion.Invoke(null, mParams);
										mParams.SetValue(6, 2);
										miOldVersion.Invoke(null, mParams);
									}

								}
								//FileSystemUtils.Set(portalSettings.PortalId, folderId, 5, -1, folderPath);
							}
							catch
							{
							} // No need to catch this
						}
						else
						{
							folderId = folderInfo.FolderID;
						}

						// By now, we should have a folderId, so we will try to add the image as a new file
						fileId = AddFile(imageFileInfo, fileName, folderPath, folderId, portalSettings.PortalId);

						//ImagePath, FileName, FolderPath, FolderI

						# region Add an entry in the itcMetaPostImages table.

						string SQL = "itcMetaPost_Insert_Image";
						object[] methodParams = {
						                        	fileId, itemId, providerKey, UserId
						                        };
						DataProvider.Instance().ExecuteNonQuery(SQL, methodParams);

						# endregion
					}
					catch
					{
					} //Do nothing since this may just be a result of another process accessing the file.
				} // End foreach (string image in images)
			} // End if (images.Count > 0)
		}

		public static void						SetTempInstallUrl(string providerKey, int tabModuleId)
		{
			DnnModuleInfoStruct mi = GetModuleInfo(tabModuleId);
			int tabId = mi.TabId;
			SetTempInstallUrl(providerKey, Globals.NavigateURL(tabId));
		}

		public static void						SetTempInstallUrl(string providerKey, string tempInstallUrl)
		{

			string sSQL = "itcMetaPost_Set_Entry_Redirect_URL";

			object[] methodParams = { providerKey, 
										HttpContext.Current.Request.UserHostAddress, 
										tempInstallUrl};
			IDataReader dr = DotNetNuke.Data.DataProvider.Instance().ExecuteReader(sSQL, methodParams);
            dr.Close();

			# region Old Approach
			//// This code temporarily sets a URL in the TempInstallUrl field of itcMetaPost
			//// This is used by the system when detecting styles.  It should be the URL of the page
			//// which WLW can use to download the styles for a newly  created page.
			//string sSQL =
			//    "UPDATE {databaseOwner}{objectQualifier}itcMetaPost SET TempInstallUrl = '"
			//    + tempInstallUrl.Replace("'", "''") + "' WHERE ItemId = 1";
			//string sURL = null;
			//IDataReader dr =
			//    (IDataReader)DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(sSQL);
			# endregion
		}

		public static void						SetTempStyleValue(int userId, string key, string value)
		{
			if (!string.IsNullOrEmpty(value))
			{
				object[] methodParams = { userId, key, value };
				string SQL = "itcmetapost_save_temp_style_text";
				DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery(SQL, methodParams);
			}
		}
		# endregion

		# region Private Static Procedures
		private static int						AddFile(ImageFileInfo imageFileInfo, string fileName, string folderPath, int folderId, int portalId)
		{
			int fileId = 0;

			FileController fileController = new FileController();

			try
			{

				fileId = fileController.AddFile(portalId, fileName,
										imageFileInfo.Extension, imageFileInfo.Size,
										imageFileInfo.Width, imageFileInfo.Height,
										imageFileInfo.ContentType, folderPath, folderId, false);

			}
			catch (Exception ex)
			{
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}

			return fileId;
		}

		private static void						FindImageMatch(string input, string regex, string regexInner, RegexOptions options, List<string> imageUrls)
		{
			MatchCollection matches = Regex.Matches(input, regex, options);
			foreach (Match match in matches)
			{
				// extract the src attribute from the image
				string regexSrc = regexInner;
				input = match.Value;
				Match src = Regex.Match(input, regexSrc, options);
				if (src != null && src.Groups["src"].Captures.Count > 0)
				{
					// We have an image Url
					imageUrls.Add(src.Groups["src"].Captures[0].Value.Replace("_itc_new_image_/", string.Empty));
				}
			}
		}

		private static ImageFileInfo			GetImageFileInformation(string physicalPath)
		{
			ImageFileInfo imageFileInfo = new ImageFileInfo();
			imageFileInfo.Extension = "png";
			imageFileInfo.ContentType = "image/png";
			imageFileInfo.Size = Null.NullInteger;
			imageFileInfo.Width = Null.NullInteger;
			imageFileInfo.Height = Null.NullInteger;

			try
			{
				Stream imageStream =
					new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read);
				Image imgImage = Image.FromStream(imageStream);
				imageFileInfo.Height = imgImage.Height;
				imageFileInfo.Width = imgImage.Width;
				imageFileInfo.Size = imageStream.Length;
				imageStream.Close();
				imageFileInfo.Extension = physicalPath.Substring(physicalPath.LastIndexOf(".") + 1);
				if (imageFileInfo.Extension != "png")
					imageFileInfo.ContentType = FileSystemUtils.GetContentType(imageFileInfo.Extension);
			}
			catch { }

			return imageFileInfo;
		}
		# endregion

		# region Obsolete Methods

		[Obsolete("This method has been replaced with GetModuleInfo.  Please use this method moving forward.")]
		public static List<DnnModuleInfoStruct> GetDnnModuleInfoStructListByProviderKey(string providerKey, int portalId)
		{
			return GetModuleInfos(providerKey, portalId);
		}
		[Obsolete("This method has been replaced by GetEditableModules")]
		public static List<DnnModuleInfoStruct> GetDnnModuleInfoStructListByProviderKeyUserIdAndPortalId(string providerKey,
			int userId, int portalId)
		{
			return GetEditableModules(providerKey, userId, portalId);
		}
		[Obsolete("This method has been replaced by GetModuleInfo(string providerKey, int userId, int portalId)")]
		public static ModuleInfoStruct[] GetModuleInfoStructsByProviderKeyUserIdAndPortalId(string providerKey, 
			int userId, int portalId)
		{
			return GetModulesForUser(providerKey, userId, portalId);
		}
		[Obsolete("This method has been replaced by GetModuleInfo(int tabModuleId)")]
		public static DnnModuleInfoStruct GetDnnModuleInfoStructByTabModuleId(int tabModuleId)
		{
			return GetModuleInfo(tabModuleId);
		}

		# endregion

	}
}
